package com.lee.ssm.controller;

import com.lee.ssm.domain.Role;
import com.lee.ssm.domain.UserInfo;
import com.lee.ssm.service.IRoleService;
import com.lee.ssm.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.security.RolesAllowed;
import java.util.ArrayList;
import java.util.List;

@Controller
@RequestMapping("/user")
public class UserController {
    @Autowired
    private IUserService iUserService;
    @Autowired
    private IRoleService iRoleService;

    @RolesAllowed("ADMIN")
    @RequestMapping("/findAll")
    public ModelAndView findAll() throws Exception {
        ModelAndView mv=new ModelAndView();

        List<UserInfo> list=iUserService.findAll();
        mv.setViewName("user-list");
        mv.addObject("userList",list);
        return mv;
    }
    @RequestMapping("/findById")

    public ModelAndView findById(String id) throws Exception {
        ModelAndView mv=new ModelAndView();

        UserInfo info=iUserService.findById(id);
        mv.setViewName("user-show");
        mv.addObject("user",info);
        return mv;

    }
    @RequestMapping("/save")
    public String save(UserInfo userInfo) throws Exception {
        iUserService.save(userInfo);

        return "redirect:findAll.do";
    }
    @RequestMapping("/findUserByIdAndAllRole")
    public ModelAndView findUserByIdAndAllRole(/*@RequestParam(name = "id")*/ String id) throws Exception {
        ModelAndView mv=new ModelAndView();

        UserInfo info=iUserService.findById(id);
//        //查询相应user已有的角色，添加角色时，不能出现已存在的角色，排除就行
//        List<Role> userRoleList=iRoleService.findByUserId(id);
//        List<Role> roleList=iRoleService.findAll();
//        List<Role> list=new ArrayList<>();
//        for (Role role : userRoleList) {
//            for (Role role1 : roleList) {
//                if (role1.getId().equals(role.getId())){
//                    list.add(role1);
//                }
//            }
//        }
//         roleList.removeAll(list);
//        查询用户除已存在的角色,即排除user_role中指定用户数据  not in(roleId from users_role where userId=?)
        List<Role> roleList=iRoleService.findOthersRoleByUserId(id);
        System.out.println(roleList);
        mv.setViewName("user-role-add");
        mv.addObject("user",info);
        mv.addObject("roleList",roleList);
        return mv;
    }
    @RequestMapping("/addRoleToUser")
    public String addRoleToUser(@RequestParam("userId") String userId, @RequestParam(name = "ids",defaultValue = "") String[] ids) throws Exception {
        if (ids==null||ids.length==0){
            return "redirect:findById.do?id="+userId;
        }
        iUserService.addRoleToUser(userId,ids);
        return "redirect:findById.do?id="+userId;
    }
}
